package cmd

import (
	"fmt"

	"os"

	"github.com/spf13/cobra"
	"github.com/uber/jaeger-lib/metrics"
	jexpvar "github.com/uber/jaeger-lib/metrics/expvar"
	jprom "github.com/uber/jaeger-lib/metrics/prometheus"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var (
	metricsBackend string
	metricsFactory metrics.Factory

	zapLogger      *zap.Logger
	configFilePath string
)

var RootCmd = &cobra.Command{
	Use:   "ldaccount",
	Short: "量子原力账号",
	Long:  "量子原力公共账号服务",
}

// initLogger logger initialize
func initLogger() {
	c := zap.NewProductionEncoderConfig()
	c.EncodeTime = zapcore.ISO8601TimeEncoder
	c.TimeKey = "time"
	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(c),
		zapcore.AddSync(os.Stdout),
		zap.NewAtomicLevelAt(zap.InfoLevel))
	zapLogger = zap.New(core, zap.AddStacktrace(zapcore.FatalLevel), zap.AddCaller())
}

func init() {
	RootCmd.PersistentFlags().StringVarP(&metricsBackend, "metrics", "m", "expvar", "Metrics backend (expvar|prometheus)")

	RootCmd.PersistentFlags().StringVarP(&configFilePath, "config-file", "c", "./config.toml", "config file for ldaccount")

	initLogger()
	cobra.OnInitialize(onInitialize)
}

// onInitialize is called before the command is executed.
func onInitialize() {
	switch metricsBackend {
	case "expvar":
		metricsFactory = jexpvar.NewFactory(10)
		zapLogger.Info("Using expvar as metrics backend")
	case "prometheus":
		metricsFactory = jprom.New().Namespace(metrics.NSOptions{Name: "gexport", Tags: nil})
		zapLogger.Info("Using Prometheus as metrics backend")
	default:
		zapLogger.Fatal("unsupported metrics backend " + metricsBackend)
	}
}

func Execute() {
	if err := RootCmd.Execute(); err != nil {
		zapLogger.Fatal(fmt.Sprintf("failed to run: %s", err.Error()))
		os.Exit(-1)
	}
}
